/*
 * @Author: Drc
 * @Date: 2021-03-24 10:52:49
 * @LastEditTime: 2021-11-03 16:15:11
 * @LastEditors: Drc
 */
import React, {useEffect, useMemo, useRef, useState} from 'react'
import {useSelector} from 'react-redux'
import Loading from 'react-native-loading-spinner-overlay'
import Toast from 'react-native-easy-toast'
import {View, FlatList, TextInput, Image} from 'react-native'
import store, {RootState} from '@path/redux'
import Theme from '@path/config/theme'
import AppNavigation from '@path/navigation/index'
import Locale from '@path/locale'
import _ from 'lodash'
import Token from '@path/config/token'
import {HostDao} from '@path/utils/http'

FlatList.defaultProps = {
  ...FlatList.defaultProps,
  scrollIndicatorInsets: {right: 1},
}

TextInput.defaultProps = {
  ...TextInput.defaultProps,
  allowFontScaling: false,
}

Image.defaultProps = {
  ...Image.defaultProps,
  resizeMode: 'contain',
  fadeDuration: 0,
}

//线上屏蔽log
if (!__DEV__) {
  global.console = {
    ...global.console,
    log: () => {},
    info: () => {},
    warn: () => {},
    error: () => {},
  }
}

const App = () => {
  const [isSetupLanguage, set_isSetupLanguage] = useState(false)
  const [isSetupTheme, set_isSetupTheme] = useState(false)
  const [isSetupToken, set_isSetupToken] = useState(false)
  const [isSetupHost, set_isSetupHost] = useState(false)

  const toastRef = useRef<Toast>()
  const isShowToast = useRef(false)

  const {loading, toast} = useSelector(
    (state: RootState) => state.utils,
    (prev, next) => _.isEqual(prev, next),
  )

  useEffect(() => {
    setupLocale()
    setupTheme()
    setupToken()
  }, [])

  useEffect(() => {
    if (!isShowToast.current && toast.text) {
      isShowToast.current = true
      toastRef.current?.show(toast.text, 1000, () => {
        store.dispatch.utils.showToast('')
        isShowToast.current = false
      })
    }
  }, [toast])

  //语言初始化
  const setupLocale = async () => {
    await Locale.init()
    set_isSetupLanguage(true)
  }

  //主题初始化
  const setupTheme = async () => {
    let theme = await Theme.getTheme()
    await Theme.setTheme(theme)
    set_isSetupTheme(true)
  }

  const setupToken = async () => {
    await Token.get()
    set_isSetupToken(true)
  }

  const setupHost = async () => {
    await HostDao.init()
    set_isSetupHost(true)
  }

  const _renderNavigation = useMemo(() => {
    return <AppNavigation />
  }, [])

  const _renderLoading = useMemo(() => {
    return <Loading {...loading} animation="fade" color={'rgba(0,0,0,0.2)'} textStyle={{color: '#fff', fontSize: 16}} />
  }, [loading])

  return (
    isSetupLanguage &&
    isSetupTheme &&
    isSetupToken && (
      <View style={{flex: 1}}>
        {_renderNavigation}
        {_renderLoading}
        <Toast
          ref={toastRef}
          position="center"
          textStyle={{color: '#fff'}}
          style={{
            backgroundColor: 'rgba(0,0,0,0.4)',
          }}
        />
      </View>
    )
  )
}

export default App
